package org.micode.libs.remoteapi;

import org.micode.common.remote.annotaion.RemoteClient;
import org.micode.common.remote.annotaion.RemoteMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

@Slf4j
public class ClientInvocationHandler implements InvocationHandler {

    private DefaultClient defaultClient;

    public ClientInvocationHandler(DefaultClient defaultClient) {
        this.defaultClient = defaultClient;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        RemoteClient remoteClient = method.getDeclaringClass()
                .getAnnotation(RemoteClient.class);
        String methodPath = getRequestMapping(method);
        //如果没有配置就使用方法名
        if (StringUtils.isBlank(methodPath)) {
            methodPath = "/" + method.getName();
        }
        String url = remoteClient.path() + methodPath;
        String serviceName = remoteClient.value();
        if (args != null && args.length > 0) {
            return this.defaultClient.request(serviceName, url, args[0],
                    method.getGenericReturnType());
        } else {
            return this.defaultClient.request(serviceName, url, null,
                    method.getGenericReturnType());
        }
    }

    /**
     * 获取请求注解
     */
    private String getRequestMapping(AnnotatedElement annotatedElement) {
        RemoteMethod remoteMethod = annotatedElement.getAnnotation(RemoteMethod.class);
        if (remoteMethod == null) {
            return null;
        }
        return remoteMethod.value();
    }

}
